package com.lty.jeeg.server.modules.sys.controller;

import java.io.*;
import java.net.URLEncoder;
import java.util.List;

import com.lty.jeeg.server.common.dto.ResponseInfo;
import com.lty.jeeg.server.common.utils.FileUtil;
import com.lty.jeeg.server.common.utils.ResponseUtil;
import com.lty.jeeg.server.modules.sys.dao.FileInfoDao;
import com.lty.jeeg.server.common.dto.LayuiFile;
import com.lty.jeeg.server.modules.sys.model.FileInfo;
import com.lty.jeeg.server.common.page.table.PageTableHandler;
import com.lty.jeeg.server.common.page.table.PageTableRequest;
import com.lty.jeeg.server.common.page.table.PageTableResponse;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.tomcat.util.http.fileupload.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.lty.jeeg.server.common.annotation.LogAnnotation;
import com.lty.jeeg.server.modules.sys.service.FileService;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author LTY
 */
@Api(tags = "文件")
@RestController
@RequestMapping("/files")
public class FileController {

	@Autowired
	private FileService fileService;

	@LogAnnotation
	@PostMapping
	@ApiOperation(value = "文件上传")
	public ResponseInfo uploadFile(MultipartFile file) throws IOException {
		return ResponseUtil.success(fileService.save(file));
	}

	/**
	 * layui富文本文件自定义上传
	 * 
	 * @param file
	 * @param domain
	 * @return
	 * @throws IOException
	 */
	@LogAnnotation
	@PostMapping("/layui")
	@ApiOperation(value = "layui富文本文件自定义上传")
	public LayuiFile uploadLayuiFile(MultipartFile file, String domain) throws IOException {
		FileInfo fileInfo = fileService.save(file);

		LayuiFile layuiFile = new LayuiFile();
		layuiFile.setCode(0);
		LayuiFile.LayuiFileData data = new LayuiFile.LayuiFileData();
		layuiFile.setData(data);
		data.setSrc(domain + "/files" + fileInfo.getUrl());
		data.setTitle(file.getOriginalFilename());

		return layuiFile;
	}

	@GetMapping
	@ApiOperation(value = "文件查询")
	@RequiresPermissions("sys:file:query")
	public PageTableResponse listFiles(PageTableRequest request) {
		return new PageTableHandler(
				request1 -> fileService.count(request1.getParams()),
				request2 -> fileService.list(
						request2.getParams(),
						request2.getOffset(),
						request2.getLimit()))
				.handle(request);
	}

	@LogAnnotation
	@DeleteMapping("/{id}")
	@ApiOperation(value = "文件删除")
	@RequiresPermissions("sys:file:del")
	public void delete(@PathVariable String id) {
		fileService.delete(id);
	}


	/**
	 * 下载文件管理中的文件
	 * xuchen
	 * @param id
	 * @param request
	 * @param response
	 */
	@LogAnnotation
	@PostMapping("/downFile/{id}")
	@ApiOperation(value = "文件下载")
	public void downFile(@PathVariable("id")String id, HttpServletRequest request, HttpServletResponse response){
		if(StringUtils.isNotEmpty(id)){
			FileInfo fileInfo = fileService.getById(id);
			String fileInfoPath = fileInfo.getPath();
			String fileName = fileInfo.getFileName();
			try {
				FileUtil.downFile(fileInfoPath,fileName,request,response);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * 根据文件名下载文件导入失败文件
	 * xuchen
	 * @param fileName
	 * @param type
	 * @param request
	 * @param response
	 */
	@LogAnnotation
	@PostMapping("/downFailFile/{fileName}/{type}")
	@ApiOperation(value = "下载导入失败文件")
	public void downFailFile(@PathVariable("fileName") String fileName,@PathVariable("type") String type,
							 HttpServletRequest request, HttpServletResponse response) {
		//当前项目路径
		String absolutePath = new File("").getAbsolutePath();
		//下载到浏览器的文件名名称
		String name = "失败信息.xls";
		if(StringUtils.isNotEmpty(type)){
			if("goods".equals(type)){
				name = "商品导入失败信息.xls";
			}
			if("stock".equals(type)){
				name = "库存导入失败信息.xls";
			}
		}
		//文件路径
		String filepath = absolutePath + File.separatorChar + "importFail" +File.separatorChar + fileName;
		try {
			FileUtil.downFile(filepath,name,request,response);
			//下载完成后将文件删除
			//FileUtils.forceDelete(new File(filepath));
			File file = new File(filepath);
			file.delete();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}


}
